package com.training.controller;

import com.training.entity.Course;
import com.training.entity.OfflinePractice;
import com.training.entity.User;
import com.training.service.CourseService;
import com.training.service.OfflinePracticeService;
import com.training.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/practice")
public class OfflinePracticeController {

    private final OfflinePracticeService practiceService;
    private final TeacherService teacherService;
    private final CourseService courseService;

    @Autowired
    public OfflinePracticeController(OfflinePracticeService practiceService, TeacherService teacherService, CourseService courseService) {
        this.practiceService = practiceService;
        this.teacherService = teacherService;
        this.courseService = courseService;
    }

    /**
     * 线下实践管理页面
     */
    @GetMapping("/manage")
    public String managePractices(@RequestParam(value = "keyword", required = false) String keyword,
                                  Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equals(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (teacherId == null) {
            model.addAttribute("errorMessage", "您不是教师，无法管理实践。");
            return "error";
        }

        List<OfflinePractice> practices = practiceService.searchPracticesByTeacher(teacherId, keyword);
        model.addAttribute("practices", practices);
        model.addAttribute("keyword", keyword);
        model.addAttribute("loggedInUser", loggedInUser);
        return "practice-manage";
    }

    /**
     * 显示创建实践的表单页面
     */
    @GetMapping("/add")
    public String showAddForm(Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null || !"TEACHER".equals(loggedInUser.getRole())) {
            return "redirect:/login";
        }
        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());

        List<Course> teacherCourses = courseService.getCoursesByTeacherId(teacherId);

        model.addAttribute("practice", new OfflinePractice());
        model.addAttribute("teacherCourses", teacherCourses);
        model.addAttribute("loggedInUser", loggedInUser);
        return "practice-add";
    }

    /**
     * 处理创建实践的表单提交
     */
    @PostMapping("/add")
    public String addPractice(@ModelAttribute("practice") OfflinePractice practice,
                              HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        practice.setTeacherId(teacherId);

        try {
            practiceService.createPractice(practice);
            redirectAttributes.addFlashAttribute("successMessage", "线下实践创建成功！");
        } catch (IllegalArgumentException e) {
            redirectAttributes.addFlashAttribute("errorMessage", "创建失败：" + e.getMessage());
            return "redirect:/practice/add"; // 返回添加页面并显示错误
        }
        return "redirect:/practice/manage";
    }

    /**
     * 查看实践详情
     */
    @GetMapping("/view/{id}")
    public String viewPractice(@PathVariable("id") Long id, Model model, HttpSession session) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) return "redirect:/login";

        OfflinePractice practice = practiceService.getPracticeById(id);

        // 权限校验：确保是该教师创建的实践
        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        if (practice == null || !practice.getTeacherId().equals(teacherId)) {
            return "redirect:/practice/manage";
        }

        model.addAttribute("practice", practice);
        model.addAttribute("loggedInUser", loggedInUser);
        return "practice-view"; // 需要创建一个 practice-view.html
    }

    /**
     * 取消实践
     */
    @PostMapping("/cancel/{id}")
    public String cancelPractice(@PathVariable("id") Long id, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        boolean success = practiceService.cancelPractice(id, teacherId);
        if (success) {
            redirectAttributes.addFlashAttribute("successMessage", "实践已成功取消！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败，可能您无权操作或实践不存在。");
        }
        return "redirect:/practice/manage";
    }

    /**
     * 结束实践
     */
    @PostMapping("/close/{id}")
    public String closePractice(@PathVariable("id") Long id, HttpSession session, RedirectAttributes redirectAttributes) {
        User loggedInUser = (User) session.getAttribute("loggedInUser");
        if (loggedInUser == null) return "redirect:/login";

        Long teacherId = teacherService.getTeacherIdByUserId(loggedInUser.getId());
        boolean success = practiceService.closePractice(id, teacherId);
        if (success) {
            redirectAttributes.addFlashAttribute("successMessage", "实践已成功结束！");
        } else {
            redirectAttributes.addFlashAttribute("errorMessage", "操作失败。");
        }
        return "redirect:/practice/manage";
    }
}